package com.jaychen.tliaswebmanagement.controller;

import com.jaychen.tliaswebmanagement.pojo.Dept;
import com.jaychen.tliaswebmanagement.pojo.Result;
import com.jaychen.tliaswebmanagement.service.DeptService;
import com.jaychen.tliaswebmanagement.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j //等同于private static final Logger log = LoggerFactory.getLogger(DeptController.class);
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpService empService;

    @GetMapping
    public Result list(){
        log.info("查询全部的部门数据");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }

    /**
     前端请求参数名与方法形参一致可省略@RequestParam，
     使用@RequestParam必须传参，其required参数默认为true
     */
    @DeleteMapping
    public Result delete(Integer id){
        Integer empNum = empService.getByDeptId(id);
        if (empNum > 0){
            log.info("根据id删除部门: {}",id);
            deptService.deleteById(id);
            return Result.success();
        } else {
            return Result.error("对不起，当前部门下有员工，不能直接删除！");
        }
    }

    @PostMapping
    public Result add(@RequestBody Dept dept){
        log.info("新增部门: {}",dept);
        deptService.add(dept);
        return Result.success();
    }

    /**
     路径参数：必须用@PathVariable，路径参数名与形参一致可简写@PathVariable("id")
     */
    @GetMapping("{id}")
    public Result getInfo(@PathVariable Integer id){
        log.info("根据id查询部门: {}",id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    @PutMapping
    public Result update(@RequestBody Dept dept){
        log.info("修改部门: {}",dept);
        deptService.update(dept);
        return Result.success();
    }
}
